import unsplash.Download;
import unsplash.Photo;
import unsplash.Unsplash;
import win.Win;

import java.io.*;
import java.util.LinkedList;
import java.util.List;

public class PhotosManager {
    private List<Photo> photos;
    private int count;

    private PhotosManager(int count) {
        this.count = count;
        File downloadDirFile = new File(downloadDirPath);
        File tmpDirFile = new File(tmpDirPath);
        if(!downloadDirFile.exists()) downloadDirFile.mkdir();
        if(!tmpDirFile.exists()) tmpDirFile.mkdir();
    }

    private static PhotosManager single;

    public static PhotosManager getPhotosManager() {
        if (single == null) single = new PhotosManager(32);
        return single;
    }

    public final String downloadDirPath = Win.getHomePath() + "\\Pictures\\Duang";
    public final String tmpDirPath = Win.getHomePath() + "\\Pictures\\Duang\\tmp";

    // 是否不是第一次加载
    private boolean notFirst;

    // 移到下一个图片
    public File next() {
        String fileName = photos.get(0).getId() + ".jpg";
        File file = new File(tmpDirPath + "\\" + fileName);
        if (!notFirst || photos.size() < 2) {
            notFirst = true;
            return file;
        }
        String nextFileName = photos.get(1).getId() + ".jpg";
        File nextFile = new File(tmpDirPath + "\\" + nextFileName);
        if (file.exists() && nextFile.exists()) {
            file.delete();
            synchronized (photos) {
                photos.remove(0);
            }
        }
        // 加载新的数据
        return nextFile;
    }

    // 仅仅更新photos，不下载
    public void requirePhotos() {
        try {
            if (photos == null) {
                synchronized (photos) {
                    photos = Unsplash.getRandomPhotos(count);
                }
                return;
            } else if (photos.size() <= count / 2) {
                synchronized (photos) {
                    photos.addAll(Unsplash.getRandomPhotos(count - photos.size()));
                }
            }
        } catch (Exception e) {
            requirePhotos();
        }
    }

    // 下载当前图片的原图
    public String DownloadCurrentPhoto() throws IOException {
        Photo p = photos.get(0);
        String fileName = p.getId() + ".jpg";
        File photoFile = new File(downloadDirPath + "\\" + fileName);
        if (!photoFile.exists()) {
            new Download(downloadDirPath, p.getUrl(), fileName).getInternetRes();
        }
        return photoFile.getAbsolutePath();
    }

    // 下载photos的缩略图
    public void DownloadRegularPhotos() {
        List<Photo> copyAry;
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(photos);
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream in = new ObjectInputStream(byteIn);
            copyAry = (List<Photo>) in.readObject();

            List<Thread> dts = new LinkedList<>();
            for (Photo cp : copyAry) {
                String fileName = cp.getId() + ".jpg";
                File photoFile = new File(tmpDirPath + "\\" + fileName);
                if (photoFile.exists()) {
                    continue;
                }
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            new Download(tmpDirPath, cp.getRegularUrl(), cp.getId() + ".jpg")
                                    .getInternetRes();
                        } catch (Exception e) {
                            synchronized (photos) {
                                for (Photo p : photos) {
                                    if (cp.getId().equals(p.getId())) {
                                        photos.remove(p);
                                    }
                                }
                            }
                        }
                    }
                });
                t.start();
                dts.add(t);
            }
            for (Thread t : dts) {
                t.join();
            }
        } catch (Exception e) {
        }
    }

    // 加载上次的缩略图文件
    public void tmpLoading() {
        File tmpDirFile = new File(tmpDirPath);
        if (!tmpDirFile.exists()) return;
        String[] fileList = tmpDirFile.list();
        if (photos == null) {
            photos = new LinkedList<>();
        }
        for (String fileName : fileList) {
            String fileId = fileName.substring(0, fileName.indexOf(".jpg"));
            Photo photo = new Photo(fileId, "https://unsplash.com/photos/" + fileId + "/download");
            photos.add(photo);
        }
    }
}
